<template>
  <view class="tip">
    <ve-button size="mini" @click="openPopup">选择文件</ve-button>
    <view class="file-name-show" v-for="(file, index) in fileList" :key="index">
      <text v-if="file.url" class="file-pdf">{{ file.fileName }}</text>
      <ve-icon name="delete_1" size="32" @click="deleteFile(index)" />
    </view>
  </view>

  <ve-toast ref="toastRef"></ve-toast>
  <ve-popup :model-value="popupValue" @close="close" mode="bottom" :maskClose="true">
    <view class="add-popup">
      <view class="tlt c1 fs36">请选择上传类型</view>
      <ve-button class="button" size="default" @click="addfile(0)">
        文件（<text v-for="(item, index) in fileTypes" :key="index"> {{ item }} {{ index + 1 != fileTypes.length ? '、' : '' }} </text>）
      </ve-button>
      <ve-button class="button" size="default" @click="addfile(1)">图片</ve-button>
    </view>
  </ve-popup>
</template>

<script setup>
  // #ifdef APP-PLUS
  import permision from '@/utils/permissionCheck/permission.js'
  // #endif
  import { ref, watch } from 'vue'
  import { getFile } from '@/api/common/index'
  import { packagedUploadFile } from '@/utils/upload-tool.js'

  const props = defineProps({
    modelValue: Array,
    fileIndex: {
      type: [String, Number],
      default: 1,
    },
    fileTypes: {
      type: Array,
      default: () => [],
    },
    // 最多支持上传文件数量
    fileNum: {
      type: [String, Number],
      default: 20,
    },
  })
  const emit = defineEmits(['update:modelValue', 'update:fileId', 'update:fileName', 'change'])

  const popupValue = ref(false)
  const openPopup = () => {
    if (fileList.value && fileList.value.length < props.fileNum) {
      popupValue.value = true
    } else {
      uni.showToast({
        icon: 'none',
        title: `文件最多支持上传${props.fileNum}个`,
      })
    }
  }
  const close = () => {
    popupValue.value = false
  }

  const progress = ref(0)
  const imageError = ref(false)
  const fileImage = ref(null) //本地暂存文件（图片）
  const fileList = ref([])

  const addfile = (type) => {
    const system = uni.getSystemInfoSync()
    console.log('机型：' + system.osName)
    console.log(type == 0 ? '文件' : '照片')
    // 检测权限
    // 文件
    if (type == 0) {
      if (system.osName == 'android') {
        permision.premissionCheck('READ_EXTERNAL_STORAGE').then((result1) => {
          console.log('result1', result1)
          if (result1 == 1) {
            popupValue.value = false
            uni.navigateTo({
              url: '/pages/utils/uploadFile?fileIndex=' + props.fileIndex + '&fileTypes=' + JSON.stringify(props.fileTypes),
            })
          }
        })
      }
      if (system.osName == 'ios') {
        popupValue.value = false
        uni.navigateTo({ url: '/pages/utils/uploadFile?fileIndex=' + props.fileIndex + '&fileTypes=' + JSON.stringify(props.fileTypes) })
      }
    }
    // 相机和照片
    if (type == 1) {
      if (system.osName == 'android') {
        permision.premissionCheck('CAMERA_EXTERNAL_STORAGE').then((result1) => {
          console.log('result1', result1)
          if (result1 == 1) {
            popupValue.value = false
            photo()
          }
        })
      }
      if (system.osName == 'ios') {
        popupValue.value = false
        photo()
      }
    }
  }
  // 选择照片
  const photo = () => {
    const maxCount = Math.min(props.fileNum - fileList.value.length, 9)
    console.log('upload-file > photo > maxCount:', maxCount)
    uni.chooseImage({
      count: maxCount,
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      success: function (res) {
        console.log('upload-file > photo > res:', res)
        uploadImage(res.tempFilePaths)
      },
    })
  }
  // 上传照片
  const toastRef = ref()
  const uploadImage = (filePathArr) => {
    console.log('upload-file > photo > 开始上传')
    toastRef.value.showLoading({ title: '正在上传中...' })
    const task = packagedUploadFile({
      filePath: filePathArr[0],
      success: (res) => {
        toastRef.value.hideLoading()
        var data = JSON.parse(res.data)
        var result = data.result[0]
        if (data.code == 200) {
          progress.value == 100
          fileList.value.push({
            url: result.openUrl,
            fileName: result.fileName,
            fileIdStr: result.fileIdStr,
          })
          emitEvent()
        } else {
          uploadError()
        }
      },
      fail: (e) => {
        console.log('upload-file > photo > 上传失败', e)

        toastRef.value.hideLoading()
        uploadError()
      },
      complete: () => {
        console.log('upload-file > photo > 上传完成', filePathArr)
        if (filePathArr.length <= 1) {
          toastRef.value.hideLoading()
          return
        }
        uploadImage(filePathArr.slice(1))
      },
    })
    task.onProgressUpdate((res) => {
      progress.value = res.progress
      if (res.progress == 100) {
        progress.value = 0
      }
    })
  }
  // 照片上传失败
  const uploadError = () => {
    progress.value = 0
    imageError.value = true
  }
  // 重试
  const retry = () => {
    uploadImage()
  }
  // 删除文件
  const deleteFile = (index) => {
    fileList.value.splice(index, 1)
    emitEvent()
  }
  // 清空文件
  const delAllFile = () => {
    fileList.value = []
    emitEvent()
  }
  // 预览pdf
  const previewPDF = () => {
    uni.downloadFile({
      url: filePDF.value.url,
      success: function (res) {
        var filePath = res.tempFilePath
        uni.openDocument({
          filePath: filePath,
          showMenu: true,
          success: function (res) {
            console.log('打开文档成功')
          },
        })
      },
    })
  }
  // 预览图片
  const previewImg = () => {
    uni.previewImage({
      urls: [filePDF.value.url],
    })
  }

  uni.$on('getFileObj', (res) => {
    let propFileIndex = props.fileIndex
    let resFileIndex = res.fileIndex
    console.log(propFileIndex, resFileIndex)
    if (propFileIndex == resFileIndex) {
      fileList.value.push({
        url: res.openUrl,
        fileName: res.fileName,
        fileIdStr: res.fileIdStr,
      })
      emitEvent()
    }
  })

  const emitEvent = () => {
    const modelValue = fileList.value?.map((it) => it.fileIdStr)
    emit('update:modelValue', modelValue)
    emit('change', modelValue)
  }

  // 获取文件pdf-img
  const getPicture = (newValue) => {
    getFile({ idList: newValue }).then((res) => {
      if (res.code == 200 && res.result) {
        fileList.value = res.result.map((it) => {
          return {
            url: it.openUrl,
            fileName: it.originalFileName, //本地文件
            fileIdStr: it.fileIdStr,
          }
        })
      }
    })
  }
  watch(
    () => props.modelValue,
    (newValue, oldValue) => {
      if (newValue && newValue.length > 0) {
        getPicture(newValue)
      }
    },
    { deep: true, immediate: true },
  )

  defineExpose({
    delAllFile,
  })
</script>

<style lang="scss" scoped>
  .tip {
    text-align: right;
    font-size: 28rpx;
    color: #191c27;
    color: #9ea5bb;
    .file-pdf {
      display: inline-block;
      text-align: right;
      color: #191c27;
      width: 394rpx;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-right: 16rpx;
    }
    .file-name-show {
      display: inline-flex;
      align-items: center;
      margin-top: 10rpx;
      margin-right: 10rpx;
    }
  }
  .list-item {
    width: 204rpx;
    height: 204rpx;
    margin-right: 20rpx;
    overflow: hidden;
    // background: rgb(244, 245, 246);
    border-radius: 8rpx;
    border: 2rpx dashed #e2e2e2;
    overflow: hidden;
    position: relative;
    border-radius: 4rpx;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    align-items: center;
    justify-content: center;
    margin-bottom: 10rpx;
  }
  .preview-wrap {
    border: 1px solid rgb(235, 236, 238);
  }
  .delete-icon {
    position: absolute;
    top: 10rpx;
    right: 0rpx;
    z-index: 1;
    border-radius: 100rpx;
    width: 44rpx;
    height: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .icon-clear-img {
    position: absolute;
    right: 10rpx;
    color: rgba(0, 0, 0, 0.8);
    width: 48rpx;
    height: 48rpx;
  }
  .progress {
    position: absolute;
    bottom: 10rpx;
    left: 8rpx;
    right: 8rpx;
    z-index: 1;
    width: auto;
  }
  .preview-image {
    display: block;
    width: 100%;
    height: 100%;
    border-radius: 4rpx;
  }
  .error-btn {
    background: rgba(0, 0, 0, 0.5);
    font-size: 20rpx;
    padding: 4px 0;
    font-size: 24rpx;
    font-weight: 400;
    color: #ffffff;
    line-height: 28rpx;
    text-align: center;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9;
    line-height: 1;
  }

  .add-popup {
    padding: 0 40rpx 64rpx;
    .tlt {
      margin: 48rpx 0;
      width: 100%;
      text-align: center;
    }
    .button {
      margin-bottom: 32rpx;
    }
  }

  .form-fee-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 23rpx;
    margin-top: 39rpx;
    .form-fee-title-text {
      font-size: 30rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #191c27;
    }
    .form-fee-title-value {
      font-size: 30rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #3072f6;
    }
  }

  .ve-form-item-disabled {
    background: #f6f8f9;
    padding-left: 32rpx;
    padding-right: 32rpx;
    color: #9ea5bb;
    .ve-form-item__body__right__content__unit {
      color: #9ea5bb;
    }

    &.leftLayout {
      .ve-form-item__body__right__content__slot {
        text-align: right;
      }
    }
  }
  .ve-form-item-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 88rpx;
    background: #f3f7ff;
    border-radius: 4rpx 4rpx 4rpx 4rpx;
    opacity: 1;
    border: 2rpx solid #3072f6;
    .ve-form-item-btn-text {
      font-size: 30rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #3072f6;
      margin-left: 18rpx;
    }
  }
  .ve-form-item-btn-have-data {
    margin-top: 32rpx;
  }
  .form-fee-content {
    background: #f7f8fa;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    opacity: 1;
    margin-bottom: 32rpx;
    .form-fee-content-title {
      height: 88rpx;
      box-sizing: border-box;
      padding: 0 24rpx 0 24rpx;
      background: #f0f1f3;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .form-fee-content-title-text {
      font-size: 30rpx;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #191c27;
    }
    .form-fee-content-content {
      box-sizing: border-box;
      padding: 0 24rpx 0 24rpx;
    }
  }
  .form-fee-borderline {
    margin-top: 32rpx;
    height: 2rpx;
    background: rgba(216, 216, 216, 0.3);
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    opacity: 1;
  }
</style>
